package com.bz.service.impl;

import com.bz.model.ChatMessage;
import com.bz.service.socket.ChatMessageRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatService {
    private static String INDEX_NAME = "chat_messages";

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    public ChatMessage saveMessage(String roomId, String userId, String message) {
        ChatMessage chatMessage = new ChatMessage(roomId, userId, message);
        chatMessageRepository.save(chatMessage);
        return chatMessage;
    }

    public List<ChatMessage> performSearch(String groupId, int from, int size) {
        IndexCoordinates indexCoordinates = IndexCoordinates.of(INDEX_NAME);
        // 检查索引是否存在，如果不存在则创建并设置映射
        if (!elasticsearchOperations.indexOps(indexCoordinates).exists()) {
            createIndexWithMapping(indexCoordinates);
            saveMessage("admin", "admin" , "欢迎来到群聊室");
            return new ArrayList<>();
        }
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("roomId", groupId))
                .withPageable(PageRequest.of(from / size, size))
                .withSort(SortBuilders.fieldSort("timestamp").order(SortOrder.DESC)) // 按照时间戳降序排列
                .build();
        SearchHits<ChatMessage> searchHits = elasticsearchOperations.search(query, ChatMessage.class);
        return searchHits.getSearchHits().stream()
                .map(SearchHit::getContent)
                .sorted(Comparator.comparing(ChatMessage::getTimestamp))
                .collect(Collectors.toList());
    }

    private void createIndexWithMapping(IndexCoordinates indexCoordinates) {
        IndexOperations indexOperations = elasticsearchOperations.indexOps(indexCoordinates);
        indexOperations.create();
    }

    public long count() {
        return chatMessageRepository.count();
    }
}